package com.itheima.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.entity.*;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;

import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Adong
 */
@Transactional
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分页查询数据
     * @param curPage
     * @param size
     * @return
     */
    @Override
    public Result findPage(Integer curPage, Integer size) {
        IPage<Category> categoryPage = new Page<>(curPage,size);
        LambdaQueryWrapper<Category> wrapper = Wrappers.lambdaQuery(Category.class);
        categoryMapper.selectPage(categoryPage,wrapper);
        List<Category> categories = categoryPage.getRecords();
        if (categories.size() == 0){
            return new Result(false, StatusCode.ERROR,"查询失败",null);
        }
        PageResult<Category> pageBean = new PageResult<>();
        pageBean.setRows(categoryPage.getRecords());
        pageBean.setTotal(categoryPage.getTotal());
        return new Result(true, StatusCode.OK,"查询成功",pageBean);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public Result findById(Integer id) {
        Category category = categoryMapper.selectById(id);
        if (category == null){
            return new Result(false,StatusCode.ERROR,"查询失败",null);
        }
        return new Result(true,StatusCode.OK,"查询成功",category);

    }

    @Override
    public Result add(Category category) {
        category.setIsMenu("0");
        category.setIsShow("1");
        category.setParentId(1);
        int insert = categoryMapper.insert(category);
        if (insert != 1){
            return new Result(false,StatusCode.ERROR,"添加失败",null);
        }
        return new Result(true,StatusCode.OK,"添加成功",insert);
    }

    @Override
    public Result updatePro(Category category) {

        int update = categoryMapper.updateById(category);
        if (update != 1){
            return new Result(false,StatusCode.ERROR,"修改失败",null);
        }
        return new Result(true,StatusCode.OK,"修改成功",update);


    }

    @Override
    public Result deleteByid(Integer id) {
        int i = categoryMapper.deleteById(id);
        if (i != 1){
            return new Result(false,StatusCode.ERROR,"删除失败",null);
        }
        return new Result(true,StatusCode.OK,"删除成功",i);
    }
}
